<?php

namespace api\modules\V1\modules\Player\controllers;

use common\helpers\VoteHelper;
use common\models\c2\entity\ActivityModel;
use common\models\c2\entity\ActivityPlayerModel;
use common\models\c2\entity\ActivityPlayerVoteRecordModel;
use common\models\c2\entity\FeUserModel;
use common\models\c2\search\ActivityPlayerSearch;
use common\models\c2\statics\ActivityPlayerType;
use common\models\c2\statics\VoteType;
use common\rest\statics\ResponseDatum;
use Yii;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\UploadedFile;

/**
 * Default controller for the `player` module
 */
class DefaultController extends \common\rest\controllers\AuthActiveController
{
    public $modelClass = 'common\models\c2\entity\ActivityPlayerModel';

    public function behaviors() {
        return ArrayHelper::merge(parent::behaviors(), [
            'authenticator' => [
                'class' => \common\rest\filters\auth\CompositeAuth::className(),
                'authMethods' => [
                    \common\rest\filters\auth\HttpBearerAuth::className(),
                    \common\rest\filters\auth\QueryParamAuth::className(),
                ],
                'optional' => [
                    'index',
                    'detail',
                ]
            ],
        ]);
    }

    /**
     * Renders the index view for the module
     * @return mixed
     */
    public function actionIndex()
    {
        $requestParams = Yii::$app->request->queryParams;
        if (!isset($requestParams['ActivityPlayerSearch']['activity_id'])) {
            return ResponseDatum::getErrorDatum(['message' => Yii::t('app.c2', 'Params Required')], false);
        }
        $searchModel = new ActivityPlayerSearch();
        $data = $searchModel->search($requestParams);

        // sort
        $sort = $data->getSort();
        $sort->defaultOrder = ['total_vote_number' => SORT_DESC];
        $data->setSort($sort);

        return $data;
    }

    /**
     * @return array|string
     * @throws \yii\db\Exception
     */
    public function actionAdd()
    {
        if (!Yii::$app->request->isPost) {
            return '|';
        }
        $db = Yii::$app->db->beginTransaction();
        $post = Yii::$app->request->post();
        $model = new ActivityPlayerModel();
        $model->loadDefaultValues();
        $model->type = ActivityPlayerType::TYPE_USER_APPLY;
        $model->user_id = Yii::$app->user->id;
        $model->setAttributes($post);
        if ($model->validate() && $model->save()) {
            try {
                $file = UploadedFile::getInstanceByName('avatar');
                $imagesUpload = new \common\helpers\ImageUploadHelper();
                $attachmentClass = \common\models\c2\entity\EntityAttachmentImage::className();
                $entityClass = \common\models\c2\entity\ActivityPlayerModel::className();
                $entityAttribute = 'avatar';
                $imagesUpload->uploadImageFile($file, $model, $attachmentClass, $entityClass, $entityAttribute);
            } catch (\Exception $e) {
                $db->rollBack();
                return ResponseDatum::getErrorDatum(['message' => Yii::t('app.c2', $e->getMessage())], $e->getMessage());
            }
            $db->commit();
            return ResponseDatum::getSuccessDatum([], $model);
        } else {
            $db->commit();
            return ResponseDatum::getErrorDatum([], $model->errors);
        }
    }

    public function actionDetail($id)
    {
        $model = ActivityPlayerModel::findOne($id);
        if (!is_null($model)) {
            $model->updateCounters(['view_number' => 1]);
            return ResponseDatum::getSuccessDatum([], $model);
        }
        return ResponseDatum::getErrorDatum(['message' => Yii::t('app.c2', 'Player not found.')], false);
    }

    public function actionFreeVote()
    {
        if (!Yii::$app->request->isPost) {
            return '|';
        }
        $params = Yii::$app->request->post();
        $message = VoteHelper::checkLimit($params['activity_player_id'], Yii::$app->user->id);
        if ($message != "ycan") {
            return ResponseDatum::getErrorDatum(['message' => $message], false);
        }
        $model = new \api\models\c2\entity\VoteRecordModel();
        $attributes = [
            'user_id' => Yii::$app->user->id,
            'type' => VoteType::TYPE_FREE,
            'activity_player_id' => $params['activity_player_id'],
            'vote_number' => 1,
            'remote' => Yii::$app->request->remoteIP,
        ];
        $model->setAttributes($attributes);
        if ($model->validate() && $model->save()) {
            return ResponseDatum::getSuccessDatum(['message' => Yii::t('app.c2', 'Vote Success')], true);
        } else {
            return ResponseDatum::getErrorDatum([], $model->errors);
        }
    }

    public function actionRankDiff($id)
    {
        $model = ActivityPlayerModel::findOne($id);
        if (!is_null($model)) {
            return ResponseDatum::getSuccessDatum([], $model->getRankDiff());
        }
        return ResponseDatum::getErrorDatum(['message' => Yii::t('app.c2', 'Player not found.')], false);
    }

}
